package com.logreview.util;

public class ByteUtil {
	
	/**
	 * 字节数组转int(注：int占4个字节)
	 * @param b
	 * @return
	 */
	public static int byteArrayToInt(byte[] b) {
		return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16
				| (b[0] & 0xFF) << 24;
	}
	
	/**
	 * int转字节数组(注：int占4个字节)
	 * @param a
	 * @return
	 */
	public static byte[] intToByteArray(int a) {
		return new byte[] { (byte) ((a >> 24) & 0xFF),
				(byte) ((a >> 16) & 0xFF), (byte) ((a >> 8) & 0xFF),
				(byte) (a & 0xFF) };
	}
	
	/**
	 * 读取指定数量的字节，如果超出范围，则返回空数组。
	 * byte[] test = {1,2,3,4,5,6,7,8,9}
	 * read(test,0,3) = {1,2,3}
	 * read(test,2,7) = {3,4,5,6,7,8,9} 
	 * @param bytes
	 * @param beginIndex 读取的下标，从0开始。
	 * @param num 读取的数量
	 * @return 
	 * @throws Exception 
	 */
	public static byte[] read(byte[] bytes,int beginIndex,int num){
		//System.out.println("beginIndex:"+beginIndex+",num:"+num);
		int index = 0;
		byte[] temp = new byte[num];
		for (int i = 0; i < bytes.length; i++) {
			if(i>= beginIndex && i<= num+beginIndex-1){
				temp[index] = bytes[i];
			    index++;
			}
		}
		return temp;
	}
	
	//高位在前，低位在后  
    public static byte[] int2bytes(int num){  
        byte[] result = new byte[4];  
        result[0] = (byte)((num >>> 24) & 0xff);//说明一  
        result[1] = (byte)((num >>> 16)& 0xff );  
        result[2] = (byte)((num >>> 8) & 0xff );  
        result[3] = (byte)((num >>> 0) & 0xff );  
        return result;  
    }  
      
    //高位在前，低位在后  
    public static int bytes2int(byte[] bytes){  
        int result = 0;  
        if(bytes.length == 4){  
            int a = (bytes[0] & 0xff) << 24;//说明二  
            int b = (bytes[1] & 0xff) << 16;  
            int c = (bytes[2] & 0xff) << 8;  
            int d = (bytes[3] & 0xff);  
            result = a | b | c | d;  
        }  
        return result;  
    }  
	
	public static void main(String[] args) {
		//byte[] test1 = new byte[5];
		//byte[] test =  {1,2,3,4,5,6,7,8,9};
		//byte[] r = read(test, 2, 3);
	}
}
